<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElTree } from 'element-plus'
import { ElTable } from 'element-plus'
import addGdfwDialog from '../dialogs/add-gdfw-dialog.vue'
import gdmbJn from '../components/gdmbJn.vue'
import xtpzService from '@/api/xtpz'
import TreeUtilDTO from '@/utils/tree'
import editorMbDialog from '../dialogs/editor-mb-dialog.vue'
import { AjglgxQueryResult } from '@/api/xtpz-dto'
import { useMainStore } from '@/store/main'

const store = useMainStore()
// 入参
const loading = ref<boolean>(false)
// 生命周期
/**
 * 初始化
 */
const showMb = ref(true)
const init = () => {
  showMb.value = true
  getTableData()
  headerIndex.value = 0
}

/**
 * 表格多选
 */
const gdfwMultipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<any[]>([])

const handleSelectionChange = (row: any[]) => {
  multipleSelection.value = row
}

// 点击每一行
const handleRowClick = (row: any) => {
  if (multipleSelection.value.includes(row)) {
    gdfwMultipleTableRef.value?.toggleRowSelection(row, false)
  } else {
    gdfwMultipleTableRef.value?.toggleRowSelection(row, true)
  }
}

/*
 * 获取已配置案件类别列表
 */
const form = ref({
  gjz: '',
})
const tableData = ref<any[]>([])
const flatTableData = ref<any[]>([])
const getTableData = () => {
  const params = {
    ...form.value,
    dwbm: store.userInfo.dwbm,
  }
  loading.value = true
  xtpzService
    .queryAjglgx(params)
    .then((res) => {
      if (res) {
        flatTableData.value = res.data.map((el) => {
          return {
            ...el,
            id: el.mlbh + '-' + el.fmlbh,
          }
        })
        tableData.value = TreeUtilDTO.getTreeData(flatTableData.value || [], 'mlbh', 'fmlbh')
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/*
 * 添加业务范围
 */
const addGdfwDialogRef = ref<InstanceType<typeof addGdfwDialog>>()
const addYwfw = () => {
  addGdfwDialogRef.value!.openDialog()
}

/*
 * 删除业务范围
 */
const deleteYwffw = () => {
  ElMessageBox.confirm('此操作将永久删除该数据，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    let ajglgxbm: any = []
    multipleSelection.value.forEach((el: any) => {
      if (el.ajglgxbm) {
        ajglgxbm.push({
          ajglgxbm: el.ajglgxbm,
        })
      }
    })
    const params = ajglgxbm
    loading.value = true
    xtpzService
      .deleteAjglgx(params)
      .then(() => {
        ElMessage.success('删除成功')
        getTableData()
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
      .finally(() => {
        loading.value = false
      })
  })
}

/*
 * 获取案件类别
 */
const treeData = ref<AjglgxQueryResult[]>([])
const firtsNode = ref<AjglgxQueryResult | null>()
const filterText = ref('')

const getAjlb = async (refresh?: boolean) => {
  // 获取案件类别
  const params = {
    gjz: filterText.value,
    dwbm: store.userInfo.dwbm,
  }
  loading.value = true
  xtpzService
    .queryAjglgxml(params)
    .then((res) => {
      if (res) {
        treeData.value = TreeUtilDTO.getTreeData(res.data || [], 'mlbh', 'fmlbh')
        if (refresh) {
          // 点击第一项
          if (treeData.value.length) {
            firtsNode.value = null
            getFirstNode(treeData.value)
            if (firtsNode.value) {
              handleCheckNode(firtsNode.value)
            }
          }
          return
        }
        handleCheckNode(currentNode.value as AjglgxQueryResult)
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 寻找第一个节点叶子结点
 */
const getFirstNode = (arr: any[]) => {
  if (firtsNode.value) {
    return
  }
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children && arr[i].children.length > 0) {
      getFirstNode(arr[i].children)
    } else {
      firtsNode.value = arr[i]
      return
    }
  }
}

/*
 * 点击树节点
 */
// 当前节点
const currentNode = ref<AjglgxQueryResult>()
const treeRef = ref<InstanceType<typeof ElTree>>()
const defaultProps = {
  children: 'children',
  label: 'mlmc',
}
const handleCheckNode = (node: AjglgxQueryResult) => {
  if (node.ajglgxbm) {
    currentNode.value = node
    // 获取表格
    getAjTableData()
    nextTick(() => {
      treeRef.value!.setCurrentKey(node.mlbh)
    })
  }
}

// 文字过滤
const filterTree = () => {
  treeRef.value?.filter(filterText.value)
}

/**
 * 树节点过滤
 */
const filterNode = (value: any, data: any) => {
  let flag = true
  if (value) {
    if (typeof value === 'string') {
      // 文字过滤
      flag = data[defaultProps.label].indexOf(value) !== -1
    }
  }
  return flag
}

// 案件模板配置
const tableAjData = ref<any[]>([])
const getAjTableData = () => {
  const params = {
    ajglgxbm: currentNode.value?.ajglgxbm || '',
  }
  loading.value = true
  xtpzService
    .queryMbpz(params)
    .then((res) => {
      if (res) {
        tableAjData.value = res.data || []
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

// const switchChange = (e: string, row: any) => {
//   const params = {
//     mbpzbm: row.mbpzbm,
//     sfqy: e,
//   }
//   xtpzService
//     .enableMbpz(params)
//     .then(() => {
//       ElMessage.success('操作成功')
//       getAjTableData()
//     })
//     .catch((err) => {
//       !err.isError && ElMessage({ type: 'warning', message: err.message })
//     })
// }
// 当前模版配置编码
const currrentMbpz = ref<any>()
const goWsjpz = (row: any) => {
  currrentMbpz.value = row
  // 获取卷内目录
  // getJnmlData()
  showMb.value = false
}

/*
 * 添加归档模板
 */
const editorMbDialogRef = ref<InstanceType<typeof editorMbDialog>>()
const addGdmb = () => {
  editorMbDialogRef.value!.openDialog(currentNode.value, 'add')
}

/*
 * 修改归档模板
 */
const editorGdmb = (row: any) => {
  editorMbDialogRef.value!.openDialog(row, 'update')
}

/*
 * 删除归档模板
 */

const deleteGdmb = () => {
  ElMessageBox.confirm('此操作将永久删除该数据，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const params = gdmbMultipleSelection.value.map((item: any) => {
      return {
        mbpzbm: item.mbpzbm as string,
      }
    })
    loading.value = true
    xtpzService
      .deleteMbpz(params)
      .then(() => {
        ElMessage.success('删除成功')
        mbRefresh()
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
      .finally(() => {
        loading.value = false
      })
  })
}

// 归档模板击每一行
const gdmbMultipleTableRef = ref()
const gdmbHandleRowClick = (row: any) => {
  if (gdmbMultipleSelection.value?.includes(row)) {
    gdmbMultipleTableRef.value?.toggleRowSelection(row, false)
  } else {
    gdmbMultipleTableRef.value?.toggleRowSelection(row, true)
  }
}

const gdmbMultipleSelection = ref<any[]>([])
const gdmbHandleSelectionChange = (val: any[]) => {
  gdmbMultipleSelection.value = val
}

/*
 * tabs 切换
 */
const headerIndex = ref(0)
const headerClickChange = (value: number) => {
  if (headerIndex.value === value) return
  headerIndex.value = value
  form.value.gjz = ''
  showMb.value = true
  if (value === 0) {
    getTableData()
  } else {
    getAjlb(true)
  }
}

const changeMb = (val: boolean) => {
  showMb.value = val
  nextTick(() => {
    treeRef.value!.setCurrentKey(currentNode.value?.mlbh)
  })
}

// 使用市院配置
const sysypz = () => {
  ElMessageBox.confirm(
    '如使用市院配置，将覆盖本院的归档范围配置和归档模板配置，是否继续？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    const params = {
      dwbm: store.userInfo.dwbm,
    }
    loading.value = true
    xtpzService
      .saveSyAjglgx(params)
      .then(() => {
        ElMessage({ type: 'success', message: '保存成功' })
        if (headerIndex.value === 0) {
          getTableData()
        } else {
          getAjlb()
        }
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
      .finally(() => {
        loading.value = false
      })
  })
}

// 模板添加/修改刷新左侧树以及表格
const mbRefresh = () => {
  getAjlb(false)
  getAjTableData()
}

defineExpose({ init })
</script>
<template>
  <div class="container jnbl-box">
    <div class="btn-box" v-if="showMb">
      <div class="gdfwpz-header">
        <button
          class="header-text"
          :class="headerIndex === 0 ? 'header-avtive' : ''"
          @click="headerClickChange(0)"
        >
          归档范围配置
        </button>
        <button
          class="header-text"
          :class="headerIndex === 1 ? 'header-avtive' : ''"
          @click="headerClickChange(1)"
        >
          归档模板配置
        </button>
        <el-link
          v-if="store.userInfo.dwbm !== '310000'"
          style="margin-left: 10px"
          type="primary"
          :underline="false"
          @click="sysypz"
          icon="Operation"
        >
          使用市院配置
        </el-link>
      </div>
      <!-- <div class="table-title">
        <span>归档范围配置</span>
      </div> -->
      <div v-if="headerIndex === 0">
        <el-input
          class="small-input"
          v-model="form.gjz"
          maxlength="100"
          placeholder="案件类别关键字"
          @change="getTableData"
        >
          <template #append>
            <el-button @click="getTableData" type="primary">查询</el-button>
          </template>
        </el-input>

        <button class="btn_operation" @click="addYwfw">
          <div class="btn-addxzaj"></div>
          添加
        </button>
        <button
          class="btn_operation"
          :disabled="multipleSelection.length === 0"
          @click="deleteYwffw"
        >
          <div class="btn-deletescaj"></div>
          删除
        </button>
        <button class="btn_operation" @click="getTableData">
          <div class="btn-refresh"></div>
          刷新
        </button>
      </div>
      <div v-else>
        <template v-if="showMb">
          <button class="btn_operation" @click="addGdmb">
            <div class="btn-addxzaj"></div>
            添加
          </button>
          <button
            class="btn_operation"
            :disabled="gdmbMultipleSelection.length === 0"
            @click="deleteGdmb"
          >
            <div class="btn-deletescaj"></div>
            删除
          </button>
          <button class="btn_operation" @click="getAjTableData">
            <div class="btn-refresh"></div>
            刷新
          </button>
        </template>
      </div>
    </div>
    <template v-if="headerIndex === 0">
      <el-table
        border
        v-loading="loading"
        ref="gdfwMultipleTableRef"
        :data="tableData"
        highlight-current-row
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column resizable prop="mlmc" label="案卷类别" />
        <el-table-column resizable prop="ywlbmc" label="业务类别" />
        <el-table-column resizable prop="ajlbmc" label="案件类别" />
      </el-table>
    </template>
    <template v-else>
      <div class="gdmb-box">
        <template v-if="showMb">
          <div class="left-box">
            <div class="left-box-title table-title">案件类别</div>
            <div class="tree-box">
              <el-input
                v-model="filterText"
                placeholder="案件类别关键字"
                @change="filterTree"
                maxlength="100"
              >
                <template #append>
                  <el-button class="search-btn" type="primary" @change="filterTree">查询</el-button>
                </template>
              </el-input>
              <el-tree
                ref="treeRef"
                node-key="mlbh"
                class="filter-tree"
                :data="treeData"
                :props="defaultProps"
                default-expand-all
                highlight-current
                @node-click="handleCheckNode"
                :filter-node-method="filterNode"
              >
                <template #default="{ data }">
                  <div class="custom-tree-node">
                    <img
                      v-if="data.sfqy === 'N'"
                      style="margin-right: 5px"
                      src="/src/assets/images/text-icon.png"
                      alt=""
                    />
                    <img
                      v-if="data.sfqy === 'Y'"
                      style="margin-right: 5px"
                      src="/src/assets/images/xswjwyz.png"
                      alt=""
                    />
                    <span class="over-title" :title="data.mlmc">{{ data.mlmc }}</span>
                  </div>
                </template>
              </el-tree>
            </div>
          </div>
          <div class="right-box">
            <el-table
              border
              v-loading="loading"
              ref="gdmbMultipleTableRef"
              :data="tableAjData"
              highlight-current-row
              @row-click="gdmbHandleRowClick"
              @selection-change="gdmbHandleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column resizable prop="ajlbmc" label="案件类别名称" />
              <el-table-column resizable prop="ajlxmc" label="案卷类别" />
              <el-table-column resizable prop="mbpzmc" label="模板名称" />
              <el-table-column resizable prop="mblxmc" label="正副案卷" />
              <el-table-column resizable prop="bz" label="备注" />
              <el-table-column resizable prop="sfqy" label="是否启用模板">
                <template #default="scope">
                  <div v-if="scope.row.sfqy === 'N' || !scope.row.sfqy">否</div>
                  <div v-else>是</div>
                </template>
              </el-table-column>
              <el-table-column resizable prop="sfqyjnml" label="是否启用卷内目录">
                <template #default="scope">
                  <div v-if="scope.row.sfqyjnml === 'N' || !scope.row.sfqyjnml">否</div>
                  <div v-else>是</div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="130">
                <template #default="scope">
                  <el-link type="primary" @click="editorGdmb(scope.row)">修改</el-link>
                  <el-link link type="primary" @click="goWsjpz(scope.row)">卷内目录</el-link>
                </template>
              </el-table-column>
            </el-table>
            <!--分页-->
            <!-- <page-export v-model="page" @changeSize="changePageSize" @changeNum="changePageNum" /> -->
          </div>
        </template>
        <template v-else>
          <gdmbJn :currrentMbpz="currrentMbpz" @changeMb="changeMb"></gdmbJn>
          <!-- <el-table
            ref="multipleTableRef"
            :data="jnlmList"
            highlight-current-row
            row-key="id"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="jnmlmc" label="题名" />
            <el-table-column prop="bz" label="备注" />
            <el-table-column label="操作" width="130">
              <template #default="scope">
                <el-link link type="primary" @click="wsgj(scope.row)">文书挂接</el-link>
              </template>
            </el-table-column>
          </el-table>
          <wsjg-dialog ref="wsjgDialogRef" :ajlbbm="currentNode?.ajlbbm" @refresh="getJnmlData" /> -->
        </template>
      </div>
    </template>

    <!--添加归档范围弹框-->
    <add-gdfw-dialog ref="addGdfwDialogRef" @refresh="getTableData" />
    <!--添加归档模板配置弹框-->
    <editor-mb-dialog
      ref="editorMbDialogRef"
      :ajglgxbm="currentNode?.ajglgxbm"
      @refresh="mbRefresh"
    />
  </div>
</template>
<style lang="scss" scoped>
.btn-box {
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;

  .gdfwpz-header {
    .header-text {
      color: #4a76ab;
    }
    .header-text + .header-text {
      margin-left: 10px;
    }
    .header-avtive {
      color: #fff;
      background-color: #3c89d0;
    }
  }
}
.jnbl-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .el-table {
    flex: 1;
    flex-shrink: 0;
    overflow: auto;
    .el-table--border::after {
      width: 0;
    }
    :deep(.el-table__cell) {
      border-right: 0 !important;
    }
    :deep(.el-table__border-left-patch) {
      display: none;
    }
    :deep(th:not(.el-table-column--selection):not(:last-child)) {
      .cell {
        border-right: 1px solid #d4d1e1;
      }
    }
  }
  :deep(.page-export) {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
.small-input {
  width: 300px;
  margin-right: 10px;
}

.gdmb-box {
  width: 100%;
  height: calc(100% - 38px);
  .left-box {
    width: 300px;
    // height: calc(100% - 38px);
    height: 100%;
    float: left;
    margin-right: 10px;
    border: 1px solid #dae4f1;
    .left-box-title {
      height: 41px;
      width: 100%;
      background-color: #ecf1fa;
      display: flex;
      align-items: center;
      padding: 0 10px;
      font-weight: bold;
    }
    .tree-box {
      width: 100%;
      height: calc(100% - 41px);
      padding: 10px;
      display: flex;
      flex-direction: column;
      overflow: auto;
      .search-btn {
        background: #409eff;
        color: #fff;
        border-bottom-left-radius: 0;
        border-top-left-radius: 0;
      }
    }
  }
  .right-box {
    width: calc(100% - 310px);
    // height: calc(100% - 38px);
    height: 100%;
    float: right;
    border: 1px solid #dae4f1;
    border-bottom: none;
    display: flex;
    flex-direction: column;
    // padding: 10px;
    .el-table {
      flex: 1;
      flex-shrink: 0;
      overflow: auto;
    }
    :deep(.page-export) {
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
}

.custom-tree-node {
  width: calc(100% - 30px);
  display: flex;
  align-items: center;
  .over-title {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}

:deep(.el-input-group__append) {
  button {
    background: #409eff;
    color: #fff;
    border-bottom-left-radius: 0;
    border-top-left-radius: 0;
    &:hover {
      background: #79bbff !important;
      color: #fff;
    }
  }
}
</style>
